<template>
  <div>
    <!-- 搜索框 -->
    <Collapse v-model="collapseShow" accordion>
        <Panel name="1">
          <div class="admin-top-right">
              <Button type="primary" @click.stop="addBtn">新增</Button>
              <Button type="error" @click.stop="batchDeletBtn">批量删除</Button>
          </div>
            <!-- <div align="right"> -->
            <!-- </div> -->
            <div slot="content">
              <Form ref="searchForm" :label-width="100" v-model="condition">
                <Row >
                  <Col span='6'>
                    <FormItem label="工号">
                        <Input  placeholder="请输入工号" clearable v-model="condition.workNo"></Input>
                    </FormItem>
                  </Col>
                  <Col span='6'>
                    <FormItem label="姓名">
                        <Input  placeholder="请输入姓名" clearable v-model="condition.name"></Input>
                    </FormItem>
                  </Col>
                  <Col span='6'>
                    <FormItem label="性别">
                      <Select v-model="condition.sex" clearable placeholder="请选择性别">
                        <Option value="0">男</Option>
                        <Option value="1">女</Option>
                      </Select>
                    </FormItem>
                  </Col>
                  <Col span='6'>
                    <FormItem label="类别">
                        <Select v-model="condition.roleKey" clearable placeholder="请选择类别">
                        <Option value="student">学生</Option>
                        <Option value="teacher">老师</Option>
                      </Select>
                    </FormItem>
                  </Col>
                </Row>
                <Row>
                  <Col span='6'>
                    <FormItem label="创建日期">
                      <!-- <Row>
                        <Col span="11">
                          <DatePicker type="date"
                            :start-date="new Date(1991, 4, 14)"
                            placeholder="起始日期"
                            ></DatePicker>
                        </Col>
                        <Col span="2"><div align="center"><span>-</span></div></Col>
                        <Col span="11">
                          <DatePicker type="date"
                            :start-date="new Date(1991, 4, 14)"
                            placeholder="截止日期"
                            ></DatePicker>
                        </Col>
                      </Row> -->
                      <DatePicker type="daterange" v-model="createdDateRange" placeholder="请选择起始和截止日期"></DatePicker>
                    </FormItem>
                  </Col>
                  <Col span='6'>
                    <FormItem label="状态">
                        <Select v-model="condition.status" clearable placeholder="请选择状态">
                        <Option value="1">未删除</Option>
                        <Option value="2">已删除</Option>
                      </Select>
                    </FormItem>
                  </Col>
                </Row>
              </Form>
               <!-- 查询重置按钮-->
              <div style="text-align:center">
                <Button type="primary"  @click="queryMethod()" class="ivu-btn ivu-btn-primary">查询</Button>
                <Button type="info"   @click="handleResetBtn('condition')" class="ivu-btn ivu-btn-dashed" style="margin-left: 8px">重置</Button>
              </div>
            </div>
        </Panel>
    </Collapse>
    <!-- 数据表格 -->
    <div >
      <Table
        size="small" border
        :stripe="true"  :columns="tableHeader"
        :data="tableData" height="500"
        style="margin-top: 12px"
        @on-selection-change="selectionChange"
        ></Table>
    </div>
    <!-- 增加和修改的模态框 -->
    <div>
      <Modal
        :title="modalTitle"
        :value = 'modalShow'
        draggable
        @on-cancel="modelCancle"
        @on-ok="handleSubmit"
        :mask-closable="modalReadonly"
        :width = 800
        ok-text="保存">
          <user-add :row="editForm" :isSuperAdmin="false"></user-add>
        <div slot="footer" v-if="footerFlag"></div>
      </Modal>
    </div>
    <!-- 修改密码模态框 -->
     <div>
      <Modal
        title="修改密码"
        :value = 'upPassModalShow'
        :mask-closable="modalReadonly"
        :closable="false"
        draggable
        ok-text="修改"
        @on-ok="upPassModalHandle"
        @on-cancel="upPassModalCancel"
        >
          <update-password :isAdmin="true" :row="upPassEntity"></update-password>
        <div slot="footer" v-if="false"></div>
      </Modal>
    </div>
    <!-- 分页组件 -->
    <div>
      <navigation :search.sync="doSearch" @navpage="pagerCallback"></navigation>
    </div>
  </div>
</template>
<script>
// import axios from '@/libs/api.request'
// import Modal from '@/view/components/modal'
import navigation from '@/view/components/navigation/navigation'
import UserAdd from './UserAdd'
import UpdatePassword from './UpdatePassword'
import httpUtil from '@/libs/httpUtil'

export default {
  name: 'User',
  components: {
    UpdatePassword,
    navigation,
    UserAdd
  },
  data () {
    return {
      upPassModalShow: false,
      upPassEntity: {},
      // 表格头
      tableHeader: [
        {
          type: 'selection',
          width: 50,
          align: 'center',
          fixed: 'left'
        },
        {
          title: '序号',
          type: 'index',
          width: 70,
          align: 'center',
          fixed: 'left'
        },
        { // 状态
          title: '状态',
          key: 'status',
          minWidth: 90,
          ellipsis: true,
          align: 'center',
          render: (h, params) => {
            let status = params.row.status
            if (status === 1) return h('span', {style: {color: '#2d8cf0', fontWeight: 'bold'}}, '未删除')
            else return h('span', {style: {color: '#ed4014', fontWeight: 'bold'}}, '已删除')
          },
          fixed: 'left'
        },
        {
          title: '工号',
          key: 'no',
          minWidth: 120,
          ellipsis: true,
          align: 'center',
          fixed: 'left'
        },

        {
          title: '姓名',
          key: 'name',
          minWidth: 90,
          ellipsis: true,
          align: 'center',
          fixed: 'left'
        },
        {
          title: '类别',
          key: 'roleName',
          minWidth: 90,
          ellipsis: true,
          align: 'center',
          render: (h, params) => {
            let roleName = params.row.roleName
            if (roleName === '学生') {
              return h('span', {
                style: {
                  color: '#19be6b'
                }
              }, roleName)
            } else {
              return h('span', {
                style: {
                  color: '#17233d'
                }
              }, roleName)
            }
          }
        },
        {
          title: '手机',
          key: 'phone',
          minWidth: 150,
          ellipsis: true,
          align: 'center'
        },
        {
          title: '性别',
          // key: 'sex',
          minWidth: 70,
          ellipsis: true,
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.sex === 0 ? '男' : '女')
          }
        },
        {
          title: '邮箱',
          key: 'email',
          minWidth: 150,
          ellipsis: true,
          align: 'center'
        },
        {
          title: '专业',
          key: 'professionName',
          minWidth: 110,
          ellipsis: true,
          align: 'center'
        },
        {
          title: '出生日期',
          key: 'birthday',
          minWidth: 110,
          ellipsis: true,
          align: 'center'
        },
        {
          title: '创建日期',
          key: 'createdAt',
          minWidth: 150,
          ellipsis: true,
          align: 'center'
          // render: (h, params) => {
          //   return h('span', {}, this.dateFormat(params.row.createdAt))
          // }
        },
        {
          title: '修改日期',
          key: 'updateAt',
          minWidth: 150,
          ellipsis: true,
          align: 'center'
        },
        {
          title: '删除日期',
          key: 'deletedAt',
          minWidth: 150,
          ellipsis: true,
          align: 'center'
        },
        {
          title: '操作',
          minWidth: 200,
          align: 'center',
          fixed: 'right',
          render: (h, params) => {
            let btns = []
            btns.push(
              h('Button',
                {
                  props: {
                    type: 'success',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.modifyBtn(params.row)
                    }
                  }
                },
                '修改'
              )
            ),
            // 修改密码
            btns.push(h(
              'Button',
              {
                props: {
                  type: 'info',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.modifyPasswordBtn(params.row)
                  }
                }
              },
              '修改密码'
            )
            )
            btns.push(h(
              'Button',
              {
                props: {
                  type: 'error',
                  size: 'small'
                },
                on: {
                  click: () => {
                    this.deleteBtn(params.row.tid)
                  }
                }
              },
              '删除'
            ))
            return h('div', btns)
          }
        }
      ],
      // 数据列表
      tableData: [],
      collapseShow: false,
      doSearch: false,
      modalTitle: '添加用户',
      modalShow: false,
      modalReadonly: false,
      footerFlag: false,
      editForm: {},
      selectArray: [],
      condition: {},
      createdDateRange: [] // 创建日期的起始截止值
    }
  },
  methods: {

    // 添加用户
    addBtn () {
      this.modalTitle = '添加用户'
      // debugger
      this.modalShow = true
      this.editForm = {}
    },

    // 取消添加模态框
    modelCancle () {
      this.modalShow = false
    },

    // 多选
    selectionChange (val) {
      this.selectArray = val
      console.log(val)
      console.log('selctArray:', this.selectArray)
      // debugger
    },

    // 保存
    handleSubmit () {
      httpUtil.asyncPost('admin/um/user/save',
        this.editForm
        , response => {
          debugger
          if (response.data.code === 200) {
            this.modalShow = false
            this.queryMethod()
            // this.addModelCancle()
            // TODO 消息提示
            this.$Message.success(response.data.msg)
          } else {
            // TODO 消息提示
            this.$Message.error(response.data.msg)
          }
        })
    },

    // 修改表格数据
    modifyBtn (row) {
      this.editForm = JSON.parse(JSON.stringify(row)) // 克隆一份，防止修改时，取消了页面值也跟着便
      // this.editForm = row
      this.modalTitle = '修改用户信息'
      this.modalShow = true
    },

    // 修改密码
    modifyPasswordBtn (row) {
      // 复制需要修改密码的对象
      this.upPassEntity = {
        userId: row.tid,
        no: row.no,
        name: row.name
      }
      this.upPassModalShow = true
    },

    // 修改密码提交
    upPassModalHandle () {
      debugger
      delete this.upPassEntity.name
      httpUtil.asyncPost('admin/um/user/updatePassword',
        this.upPassEntity,
        res => {
          alert(res.data.msg)
        })
      this.upPassModalCancel()
    },

    // 修改密码取消
    upPassModalCancel () {
      this.upPassModalShow = false
      this.upPassEntity = {}
    },

    // 删除表格数据
    deleteBtn (id) {
      debugger
      id += ','
      this.handleDelete(id)
    },

    // 批量删除
    batchDeletBtn () {
      let select = this.selectArray
      let ids = ''
      // 判断有无选择
      if (select.length > 0) {
        select.forEach((entity, n) => {
          ids = ids + entity.tid + ','
        })
        this.handleDelete(ids)
      } else {
        this.$Message.warning('请先选择需要删除的选项')
      }
    },

    // 向后端请求删除操作
    handleDelete (ids) {
      httpUtil.asyncDelete('admin/um/user/delete', {
        'ids': ids
      }, res => {
        if (res.data.code === 200) {
          alert(res.data.msg)
          this.queryMethod()
        } else {
          alert(res.data.msg)
        }
      })
    },

    // 搜索重置
    handleResetBtn () {
      this.$refs['searchForm'].resetFields()
      this.condition = {}
      this.createdDateRange = ['', '']
      this.queryMethod()
    },

    // 点击翻页
    pagerCallback (page, search) {
      let option = {
        url: 'admin/um/user/queryByCondition',
        pageData: page,
        success: (response) => {
          this.tableData = response.data.records
        }
      }
      if (search) {
        option.params = {
          data: this.condition
        }
      }
      this.$httpUtil.pageSearch(option)
    },
    dateFormat (time) {
      if (time) {
        let date = new Date(time)
        return date.format('yyyy-MM-dd')
      } else {
        return ''
      }
    },
    queryMethod () {
      if (this.createdDateRange[0] !== '') { // 如果选择了日期，取出起始值
        this.condition.createdDateStart = this.createdDateRange[0]
        this.condition.createdDateEnd = this.createdDateRange[1]
      }
      this.doSearch = true
    }
  },
  mounted: function () {
    // this.getAdminData()
    this.queryMethod()
  }
}
</script>
